package sh.base.aop;

import lombok.extern.slf4j.Slf4j;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * 生成代理对象
 * 需要拦截的对象都是有关联查询的
 *
 * @author lqq
 * @date 2019/1/28
 */
@Slf4j
public class CglibProxy extends AopProxy implements MethodInterceptor {


    /**
     * 源对象信息
     */
    private TargetSource targetSource;

    private Object targetObject;


    CglibProxy(TargetSource targetSource, org.aopalliance.intercept.MethodInterceptor methodInterceptor){
        this.targetSource = targetSource;
        this.methodInterceptor = methodInterceptor;
    }

    @Override
    public Object intercept(Object obj, Method method, Object[] args,
                            MethodProxy proxy) throws Throwable {

        return this.methodInterceptor.invoke(new ReflectiveMethodInvocation(targetSource.getTarget(), method, args));
        //通过统一入口执行逻辑
        //return this.proxyFacade.intercept(obj, method, args, proxy);
    }

    @Override
    public Object getProxy() {
        //传入用户类
        this.targetObject = targetSource.getTarget();
        //Enhancer是cglib的核心类
        Enhancer enhancer = new Enhancer();

        // 将用户类设为 Enhancer对象的superclass属性,,即设为 Enhancer对象的父类
        enhancer.setSuperclass(targetSource.getClazz());
        // 设 Enhancer对象的Callbacks属性,要求必须是Callback接口类型
        enhancer.setCallback(this);
        //生成代理对象
        return enhancer.create();
    }
}